import { useWebSocket } from "@vueuse/core";

class WebSocket {
  constructor() {
    this.socketStatus = null; // WebSocket 状态
    this.socketData = null;   // WebSocket 消息
    this.sendMessage = null;     // 发送消息的方法
    this.isConnected = false;    // 是否已连接
    this.url = null;             // WebSocket 连接的 URL
  }

  connectWebSocket(url) {
    this.url = url;
    if (this.isConnected) {
      console.log("WebSocket 已经连接，无需重新连接");
      return;
    }

    const { status, data, send, close } = useWebSocket(url, {
      autoReconnect: {
        retries: 3,
        delay: 1000,
        onFailed: () => {
          this.socketInstance = null;
          // 断开连接后，重新初始化
          this.initializeSocket();
        },
      }, // 自动重连
      heartbeat: {
        interval: 5000,
        pongTimeout: 3000,
      }, // 心跳
      onConnected: () => {
        console.log("WebSocket 已连接");
        this.isConnected = true;
      },
      onDisconnected: () => {
        console.log("WebSocket 已断开");
        this.isConnected = false;
      },
      onError: (e) => console.error("WebSocket 错误:", e),
      onMessage: (ws, e) => {
        // console.log("收到消息:", e.data);
        if (this.socketData) {
          this.socketData(JSON.parse(e.data));
        }
      },
      // webSocketOptions: {
      //   headers: {
      //     // 必须明确允许浏览器附加 Cookie
      //     withCredentials: true,
      //   },
      // },
    });

    this.socketStatus = status;
    this.sendMessage = send;
    this.close = close;
  }

  initializeSocket() {
    console.log("WebSocket 已重新初始化");
    this.connectWebSocket(this.url);
  }

  disconnectWebSocket() {
    if (this.close) {
      this.close();
      this.isConnected = false;
      console.log("WebSocket 已手动断开");
    }
  }

  sendMessageToServer(message) {
    if (this.sendMessage) {
      this.sendMessage(message);
    } else {
      console.error("WebSocket 未连接，无法发送消息");
      this.socketInstance = null;
      this.initializeSocket();
      this.sendMessage(message);
    }
  }
}

export default WebSocket;
